<?php


namespace Module\DyAi\Admin\Controller;


use Illuminate\Routing\Controller;
use ModStart\Admin\Concern\HasAdminQuickCRUD;
use ModStart\Admin\Layout\AdminConfigBuilder;
use ModStart\Admin\Layout\AdminCRUDBuilder;
use ModStart\Admin\Layout\AdminPage;
use ModStart\Core\Dao\ModelUtil;
use ModStart\Core\Input\Request;
use ModStart\Core\Util\RandomUtil;
use ModStart\Field\AbstractField;
use ModStart\Field\AutoRenderedFieldValue;
use ModStart\Grid\Displayer\ItemOperate;
use ModStart\Grid\Grid;
use ModStart\Grid\GridFilter;
use ModStart\Support\Concern\HasFields;
use ModStart\Core\Input\Response;
use ModStart\Widget\TextDialogRequest;
use Module\Cms\Type\CmsMode;
use Module\DyAi\Model\DownContent;
use Module\DyAi\Model\DyAiCategory;
use Module\DyAi\Util\DyAiKeysuggUtil;
use Module\DyAi\Util\DyAiZhuanjiUtil;
use ModStart\Core\Util\CRUDUtil;
use ModStart\Form\Form;
use Module\DyAi\Model\DyAiKeysugg;
use Module\DyAi\Type\KeysuggStatus;

class DyAiKeysuggController extends Controller
{
    use HasAdminQuickCRUD;

    protected function cruds(AdminCRUDBuilder $builder)
    {
        $builder
            ->init(DyAiKeysugg::class)
            ->field(function ($builder) {
                /** @var HasFields $builder */
                $builder->id('id', 'ID');
                $builder->text('keyword', '关键词');
                $builder->text('search_keyword', '搜索关键词');
                $builder->text('soft_size', '软件数量');
                //$builder->json('sugg_json', 'json数据')->listable(false);
                $builder->type('status', '状态')->type(KeysuggStatus::class, [
                    KeysuggStatus::WAIT => 0,
                    KeysuggStatus::CANCEL => 'danger',
                    KeysuggStatus::ADOPT => 'success',
                ])->required();
                $builder->display('created_at', L('Created At'))->listable(true);
                $builder->display('updated_at', L('Updated At'))->listable(true);

				//$builder->jsonIdItems('sugg_json', 'jsonIdItems');
                $builder->canBatchSelect(true);
				$builder->batchOperatePrepend('<button class="btn btn-success" data-batch-confirm="确认加入 %d 个专辑生成列表？" data-batch-operate="' . modstart_admin_url('dy_ai/keysugg/createZhuanji') . '"><i class="iconfont icon-check-simple"></i> 加入专辑</button>'.
				'<button class="btn btn-danger" data-batch-confirm="确认取消 %d 个下拉词？" data-batch-operate="' . modstart_admin_url('dy_ai/keysugg/cancel') . '"><i class="iconfont icon-close"></i> 取消</button>');
            })
            ->gridFilter(function (GridFilter $filter) {
                $filter->eq('id', L('ID'));
                $filter->like('keyword', L('Title'));
                $filter->eq('status', '状态')->autoHide(false)->select(KeysuggStatus::class);
            })
            ->hookChanged(function (Form $form) {
                DyAiKeysuggUtil::clearCache();
            })
            ->title('下拉词列表')
            ->canSort(false)
            ->canEdit(false);
    }

    public function index(AdminPage $page)
    {
        $grid = Grid::make('dy_ai_keysugg');
        $grid->id('id', 'ID');
        $grid->text('keyword', '关键词');
        $grid->text('search_keyword', '搜索关键词');
        $grid->json('sugg_json', 'json数据')->listable(false);
        $grid->type('status', '状态')->type(KeysuggStatus::class, [
            KeysuggStatus::WAIT => 0,
            KeysuggStatus::CANCEL => 'danger',
            KeysuggStatus::ADOPT => 'success',
        ])->required();
        $grid->gridFilter(function (GridFilter $filter) {
            $filter->eq('id', L('ID'));
            $filter->like('keyword', L('Title'));
            $filter->eq('status', '状态')->autoHide(false)->select(KeysuggStatus::class);
        });
        $grid->display('created_at', L('Created At'))->listable(true);
        $grid->display('updated_at', L('Updated At'))->listable(true);
        $grid->display('soft_size', L('软件数量'))->listable(true)->sortable(true);

        $grid->title('下拉词列表')->dialogSizeSmall();
        $grid->canBatchSelect(true);
        $grid->batchOperatePrepend('<button class="btn btn-success" data-batch-confirm="确认加入 %d 个专辑生成列表？" data-batch-operate="' . modstart_admin_url('dy_ai/keysugg/createZhuanji') . '"><i class="iconfont icon-check-simple"></i> 加入专辑</button>'.
            '<button class="btn btn-danger" data-batch-confirm="确认取消 %d 个下拉词？" data-batch-operate="' . modstart_admin_url('dy_ai/keysugg/cancel') . '"><i class="iconfont icon-close"></i> 取消</button>');
        $grid->canShow(true)->urlAdd(action('\\' . __CLASS__ . '@show'));
        $grid->canAdd(false)->urlAdd(action('\\' . __CLASS__ . '@edit'));
        $grid->canEdit(false)->urlEdit(action('\\' . __CLASS__ . '@edit'));
        $grid->canDelete(true)->urlDelete(action('\\' . __CLASS__ . '@delete'));
        $grid->hookItemOperateRendering(function (ItemOperate $itemOperate) {
            $item = $itemOperate->item();
            $fieldDialog = new TextDialogRequest();
            $fieldDialog->type('primary');
            $fieldDialog->text('<i class="iconfont icon-tools"></i> 查看软件');
            $fieldDialog->url(action('\\' . __CLASS__ . '@down_list', ['id' => $item->id]));
            $fieldDialog->width('90%');
            $fieldDialog->height('90%');
            $itemOperate->prepend($fieldDialog);
        });
        if (Request::isPost()) {
            return $grid->request();
        }
        return $page->pageTitle('下拉词列表')->body($grid);
    }

    public function down_list(AdminConfigBuilder $builder)
    {
        $builder->useDialog();
        $builder->pageTitle('软件列表');
        $id = CRUDUtil::id();
        if($id){
            $sugg = ModelUtil::get(DyAiKeysugg::class, $id);
            $all_dep = DyAiCategory::all();
            foreach($all_dep as $a_i=>$dep) {
                $downs = [];
                $query = DownContent::whereRaw("ai_json LIKE ?", ["%\"{$sugg['keyword']}\"%"])->where('categoryId',$dep['id'])->get()->toArray();//where('ai_json', 'like', '%' . $sugg['keyword'] . '%')->
                foreach ($query as $r) {
                    $downs[] = ['id' => $r['down_id'], 'title' => $r['title']];
                }
                if(count($downs)>0){
                $builder->complexFieldsList('downs'.$dep['id'], $dep['title'].'软件列表')->fields([
                    ['name' => 'id', 'title' => 'ID', 'type' => 'text', 'defaultValue' => '', 'placeholder' => '', 'tip' => '',],
                    ['name' => 'title', 'title' => '标题', 'type' => 'text', 'defaultValue' => '', 'placeholder' => '', 'tip' => '',],
                ])->defaultValue($downs);
                }
            }
        }
        return $builder->perform();
    }
	
	public function cancel()
    {
        DyAiKeysuggUtil::updateStatus(CRUDUtil::ids(),KeysuggStatus::CANCEL);
        return Response::redirect(CRUDUtil::jsGridRefresh());
    }
	
	public function createZhuanji()
    {
        DyAiKeysuggUtil::addZhuanji(CRUDUtil::ids());
        return Response::redirect(CRUDUtil::jsGridRefresh());
    }

}
